package com.xgc.book.bookserver.controller;

import com.xgc.book.bookserver.service.CodeService;
import com.xgc.book.bookserver.service.TokenService;
import com.xgc.book.bookserver.service.UserinfoService;
import com.xgc.book.bookserver.util.ResultJson;
import com.xgc.book.bookserver.util.form.LoginForm;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassNameLoginController
 * @Author:王润之
 * @Description
 * @DateTime2023/11/21 13:49
 **/
@RestController
public class LoginController extends BaseLoginController {
    @Autowired
    private CodeService codeService;
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private TokenService tokenService;

    @GetMapping("/kaptcha.jpg")
    public void kaptcha(HttpServletResponse response, String uuid) throws IOException {
        /*设置输出头*/
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        /*获取输出流*/
        ServletOutputStream out = response.getOutputStream();
        /*输出内容到浏览器*/
        ImageIO.write(codeService.createKaptcha(uuid), "jpg", out);
        /*IO工具--专门用来在流结束后自动关闭的*/
        IOUtils.closeQuietly(out);
    }

    @PostMapping("/login")
    public ResultJson login(@RequestBody LoginForm loginForm) {
        return userinfoService.login(loginForm);
    }

    @PostMapping("/logout")
    public ResultJson logout() {
        tokenService.saveToken(getLoginId());
        return ResultJson.ok();
    }
}
